package com.pms.actions;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pms.businesslogic.AuthenticationManager;
import com.pms.framework.Action;
import com.pms.framework.JSPUtility;
import com.pms.platform.dto.User;

public class LoginAction implements Action {

	public void execute(HttpServletRequest request,HttpServletResponse response){

		Hashtable error =(Hashtable) request.getAttribute("error");
		try {
			if(error.size() > 0)
			{
				if(error.containsKey("InvalidLogin") || error.containsKey("illegalAccess")) {
					request.setAttribute("nextPageToken", "needLogin");
					request.setAttribute("plainPage", "TRUE");
					return;
				}
				request.setAttribute("plainPage", "TRUE");
				request.setAttribute("nextPageToken", "failure");
				return;
			}

			// Store it for further process request
			String login = JSPUtility.GetNonEmptyString(request, "login");
			String password = JSPUtility.GetNonEmptyString(request, "password");
			String vendorCode= JSPUtility.GetNonEmptyString(request, "vendorCode");
			User user=new AuthenticationManager().validateLogin(login, password,vendorCode);


			if(user!=null){
				/*if(user.getStatus()==0){
					error.put("error", "Your status is in active. ");
					request.setAttribute("error",error);
					request.setAttribute("plainPage", "TRUE");
					request.setAttribute("nextPageToken", "failure");
					return;
				}*/


				request.getSession().setAttribute("user", user);

				if(user.getUserId()== User.SUPER_ADMIN_ID && user.getVendor_Code()== User.ROOT_VENDOR_CODE){
					request.getSession().setAttribute("isSuperAdmin", true);
				}else{
					//HashMap<Long, String> accessControlsMap=AclDao.getInstance().findUserPermission(user.getUserId());
					//request.getSession().setAttribute("accessControlsMap", accessControlsMap);
					
					//System.out.println("@@@@@@@@@@@@@ accessMap 11 ==> "+accessControlsMap.size());
					/*Iterator<Long> en=accessControlsMap.keySet().iterator();
					while(en.hasNext()){
						Long lk=en.next();
						System.out.println(" @@@@@ key "+ lk +" val == "+ accessControlsMap.get(lk));
					}*/
				}

				request.setAttribute("nextPageToken", "success");
			}else{
				error.put("error", "Wrong User Id or Password");
				request.setAttribute("error",error);
				request.setAttribute("plainPage", "TRUE");
				request.setAttribute("nextPageToken", "failure");
			}

		}catch (Exception e) {

			if(e.getMessage().contains("Invalid")){
				error.put("error", e.getMessage());
			}else {
				error.put("error","Wrong User Id or Password");
			}

			request.setAttribute("error",error);
			request.setAttribute("plainPage", "TRUE");
			request.setAttribute("nextPageToken", "failure");
			return;
		}
	}

}
